#!/bin/bash
################################################################################
# DCR Explorer Dashboard - Tony's Director64
# Native macOS "Click-to-Launch" Edition
################################################################################

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
RESOURCES_DIR="$SCRIPT_DIR"

if [ -f "/opt/homebrew/bin/brew" ]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f "/usr/local/bin/brew" ]; then
    eval "$(/usr/local/bin/brew shellenv)"
fi

export WINEPREFIX="$HOME/.wine"

# ── Determine Scan Dir ────────────────────────────────────────────────────────
if [ -n "$1" ] && [ -d "$1" ]; then
    DEFAULT_DIR="$1"
else
    # Resources is App.app/Contents/Resources
    # ../../.. is 1:Contents, 2:App.app, 3:ParentFolder
    DEFAULT_DIR="$( cd "$SCRIPT_DIR/../../.." && pwd )"
fi

# Detect App Translocation
IS_TRANS_L=false
if [[ "$SCRIPT_DIR" == *"/AppTranslocation/"* ]]; then
    IS_TRANS_L=true
fi

# ── Auto-scan ─────────────────────────────────────────────────────────────────
# We try to scan the default directory first.
SCAN_DIR="$DEFAULT_DIR"
FILES_FOUND=$(find "$SCAN_DIR" -maxdepth 1 -iname "*.dcr" -type f 2>/dev/null | wc -l | tr -d ' ')

SCAN_DIR="${SCAN_DIR%/}"
[ -z "$SCAN_DIR" ] && exit 0

# ── Find Projector.exe ────────────────────────────────────────────────────────
GAME_DIR="$HOME/.director64_data/game"
PROJECTOR=$(find "$GAME_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)
[ -z "$PROJECTOR" ] && PROJECTOR=$(find "$RESOURCES_DIR" -iname "projector.exe" -type f 2>/dev/null | head -n 1)
PROJECTOR_DIR="$( cd "$( dirname "$PROJECTOR" )" && pwd )"
PROJECTOR_NAME="$( basename "$PROJECTOR" )"

# ── Scan for DCR Files ────────────────────────────────────────────────────────
TMPFILE=$(mktemp /tmp/dcr_list_XXXXXX.txt)
find "$SCAN_DIR" -maxdepth 1 -iname "*.dcr" -type f 2>/dev/null | sort > "$TMPFILE"

LABELS=()
PATHS=()
AS_LIST=""

while IFS= read -r fpath; do
    [ -z "$fpath" ] && continue
    fname=$(basename "$fpath")
    
    # Get size
    bytes=$(stat -f%z "$fpath" 2>/dev/null || echo 0)
    size=$(echo "scale=1; $bytes/1048576" | bc 2>/dev/null || echo 0)
    
    label="◈ $fname ($size MB)"
    LABELS+=("$label")
    PATHS+=("$fpath")
    
    escaped=$(printf '%s' "$label" | sed 's/"/\\"/g')
    if [ -n "$AS_LIST" ]; then AS_LIST="$AS_LIST, \"$escaped\""; else AS_LIST="\"$escaped\""; fi
done < "$TMPFILE"
rm -f "$TMPFILE"

if [ -z "$AS_LIST" ]; then
    osascript -e "display dialog \"No .dcr files found in: \n\n$SCAN_DIR\" buttons {\"OK\"} with icon caution"
    exit 0
fi

# ── Native Click-to-Launch Dialog ─────────────────────────────────────────────
# Double-clicking an item in this list triggers it instantly.
CHOSEN=$(osascript <<APPLESCRIPT
set theList to {$AS_LIST}
set chosen to choose from list theList \
    with title "DCR Dashboard" \
    with prompt "DOUBLE-CLICK DCR TO LAUNCH INSTANTLY:" \
    OK button name "Launch Selected" \
    cancel button name "Cancel"
if chosen is false then return "__CANCEL__"
return item 1 of chosen
APPLESCRIPT
)

if [ "$CHOSEN" = "__CANCEL__" ] || [ -z "$CHOSEN" ]; then exit 0; fi

# Match choice to path
SELECTED_PATH=""
for i in "${!LABELS[@]}"; do
    if [ "${LABELS[$i]}" = "$CHOSEN" ]; then
        SELECTED_PATH="${PATHS[$i]}"
        break
    fi
done

if [ -n "$SELECTED_PATH" ]; then
    # ── Prepare & Launch ──────────────────────────────────────────────────────────
    SELECTED_NAME=$(basename "$SELECTED_PATH")
    SELECTED_DIR=$(dirname "$SELECTED_PATH")

    LAUNCH_LINK="$PROJECTOR_DIR/launch.dcr"
    rm -f "$LAUNCH_LINK"
    cp "$SELECTED_PATH" "$LAUNCH_LINK" 2>/dev/null

    # Copy videos
    VIDEO_EXTS="mp4 mov avi qt mpg mpeg m4v wmv flv f4v swf"
    for ext in $VIDEO_EXTS; do
        for vf in "$SELECTED_DIR/"*."$ext" "$SELECTED_DIR/"*."$(echo "$ext" | tr '[:lower:]' '[:upper:]')"; do
            [ -f "$vf" ] && cp -n "$vf" "$PROJECTOR_DIR/" 2>/dev/null
        done
    done

    pkill -9 wine 2>/dev/null
    pkill -9 wineserver 2>/dev/null
    sleep 1

    osascript -e "display notification \"Launching: $SELECTED_NAME\" with title \"DCR Explorer\""
    cd "$PROJECTOR_DIR" || exit 1
    wine "$PROJECTOR_NAME" "launch.dcr" &>/dev/null &

    sleep 10
    rm -f "$LAUNCH_LINK" 2>/dev/null
fi
exit 0
exit 0
